package com.jie.erp.springbootjieerp.controller;

import com.jie.erp.springbootjieerp.bean.JepRole;
import com.jie.erp.springbootjieerp.bean.JepUser;
import com.jie.erp.springbootjieerp.service.JepRoleService;
import com.jie.erp.springbootjieerp.service.JepUserService;
import com.jie.erp.springbootjieerp.utils.EbMJUtis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private JepUserService jepUserService;

    @Autowired
    private JepRoleService jepRoleService;

    /**
     * 用户管理
     */
    @GetMapping("/users")
    public String getUsers(Model model){
        List<JepUser> jepUsers = jepUserService.selectUsers();
        model.addAttribute("uList",jepUsers);
        return "emp/userlist";
    }

    /**
     * 角色管理
     */
    @GetMapping("/roles")
    public String getRoles(Model model){
        List<JepRole> roleList = jepRoleService.getRoleAll();
        model.addAttribute("rList",roleList);
        return "emp/rolelist";
    }

    /**
     * 查询用户下的角色
     */
    @GetMapping("/assignRole/{id}")
    public String assignRole(@PathVariable("id") Integer id,Model model){
        List<JepRole> jepRoles = jepUserService.selectUserAndRole(id);
        model.addAttribute("userId",id);
        model.addAttribute("roles",jepRoles);
        return "emp/assignRole";

    }

    /**
     * 分配角色
     */
    @PostMapping("/castRole")
    public void castRole(Integer userId,String roles, HttpServletResponse response){
        jepUserService.assignRoleByUser(userId,roles);
        EbMJUtis.printAjax(response,"success");
    }


    /**
     * 修改用户页面
     */
    @GetMapping("/update/{id}")
    public String userUpdate(@PathVariable("id") Integer userId,Model model){
        JepUser user = jepUserService.getUserById(userId);
        model.addAttribute("user",user);
        return "emp/add";
    }

    /**
     * 用户修改
     */
    @PutMapping("/user")
    public String updateUser(JepUser user){
        jepUserService.updateUser(user);
        return "redirect:/users";
    }

    /**
     * 用户添加
     */
    @PostMapping("/user")
    public String saveUser(JepUser user){
        jepUserService.saveUser(user);
        System.out.println("------------------------------");
        return "redirect:/users";
    }
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable("id") Integer id){
        jepUserService.deleteUserById(id);
        return "redirect:/users";
    }


}
